import 'dart:async';

import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:common/common.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../world/world_audio_publish/water_button.dart';

class WaveformsPlayerWidget extends StatefulWidget {
  final String audioPath;
  final double width;
  final double waveformsHeight;
  final EdgeInsets padding;
  final EdgeInsets margin;
  final double radius;

  const WaveformsPlayerWidget({
    super.key,
    required this.audioPath,
    this.width = 200,
    this.waveformsHeight = 70,
    this.padding = const EdgeInsets.only(bottom: 6, right: 10, top: 6),
    this.margin = const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
    this.radius = 8,
  });

  @override
  State<WaveformsPlayerWidget> createState() => _WaveformsPlayerWidgetState();
}

class _WaveformsPlayerWidgetState extends State<WaveformsPlayerWidget> {
  late PlayerController? controller;
  late StreamSubscription<PlayerState>? playerStateSubscription;
  late StreamSubscription<int>? playerDurationSubscription;
  // final playerWaveStyle =
  //     const PlayerWaveStyle(fixedWaveColor: Colors.white54, liveWaveColor: Colors.white, spacing: 6);

  int totalDuration = 0;

  @override
  void initState() {
    super.initState();
    controller = PlayerController();
    _preparePlayer();
    playerStateSubscription = controller?.onPlayerStateChanged.listen((_) {
      totalDuration = controller!.maxDuration;
      logs('totalDuration = $totalDuration');
      setState(() {});
    });
    playerDurationSubscription = controller?.onCurrentDurationChanged.listen((int duration) {
      totalDuration = controller!.maxDuration - duration;
      setState(() {});
    });
  }

  void _preparePlayer() async {
    controller?.preparePlayer(path: widget.audioPath, shouldExtractWaveform: true);
    // controller!
    //     .extractWaveformData(path: widget.audioPath, noOfSamples: playerWaveStyle.getSamplesForWidth(widget.width))
    //     .then((waveformData) => logs(waveformData.toString()));
  }

  @override
  void dispose() {
    clearController();
    super.dispose();
  }

  void clearController() {
    try {
      playerStateSubscription?.cancel();
      playerDurationSubscription?.cancel();
      controller?.dispose();
    } catch (e) {
      logs(e.toString());
      //
    }
  }

  @override
  Widget build(BuildContext context) {
    return widget.audioPath.isEmpty ? const SizedBox.shrink() : _buildAudioPlayButtonWarpper();
    // : Align(
    //     alignment: Alignment.center,
    //     child: Container(
    //       padding: widget.padding,
    //       margin: widget.margin,
    //       decoration:
    //           BoxDecoration(borderRadius: BorderRadius.circular(widget.radius), color: const Color(0xFF25D4D0)),
    //       child: Row(
    //         mainAxisSize: MainAxisSize.min,
    //         children: [
    //           if (!controller!.playerState.isStopped)
    //             IconButton(
    //               onPressed: () async {
    //                 controller!.playerState.isPlaying
    //                     ? await controller!.pausePlayer()
    //                     : await controller!.startPlayer();
    //                 controller!.setFinishMode(finishMode: FinishMode.pause);
    //               },
    //               icon: Icon(controller!.playerState.isPlaying ? Icons.stop : Icons.play_arrow),
    //               color: Colors.white,
    //               splashColor: Colors.transparent,
    //               highlightColor: Colors.transparent,
    //             ),
    //           // AudioFileWaveforms(
    //           //   // size: Size(MediaQuery.of(context).size.width / 2, widget.waveformsHeight),
    //           //   size: Size(widget.width, widget.waveformsHeight),
    //           //   playerController: controller!,
    //           //   waveformType: WaveformType.fitWidth,
    //           //   // waveformType: WaveformType.long,
    //           //   playerWaveStyle: playerWaveStyle,
    //           // ),
    //           Container(
    //               margin: const EdgeInsets.only(left: 10, right: 10),
    //               child: Text('${((totalDuration / 1000).toStringAsFixed(0))}s',
    //                   style: TextStyle(color: Colors.white, fontSize: 13.sp, fontWeight: FontWeight.bold))),
    //           // const SizedBox(width: 10),
    //         ],
    //       ),
    //     ),
    //   );
  }

// 播放声音按钮
  Widget _buildAudioPlayButtonWarpper() {
    return Container(
        padding: const EdgeInsets.only(bottom: 50),
        child: Column(
          children: [
            Stack(
              children: [
                Container(
                    width: 100,
                    height: 100,
                    color: Colors.transparent,
                    child: controller!.playerState.isPlaying
                        ? const ACEWaterButton(color: Color(0xFFE9FAFA))
                        : const SizedBox()),
                Positioned.fill(
                  child: GestureDetector(
                    onTap: () async {
                      // controller!.playerState.isPlaying
                      //     ? await controller!.pausePlayer()
                      //     : await controller!.startPlayer();
                      // controller!.setFinishMode(finishMode: FinishMode.pause);
                      if (controller!.playerState.isPlaying) {
                        await controller!.pausePlayer();
                        await controller!.seekTo(0);
                      } else {
                        await controller!.startPlayer();
                      }
                      controller!.setFinishMode(finishMode: FinishMode.pause);
                      // controller!.setFinishMode(finishMode: FinishMode.stop);
                    },
                    child: Center(child: Image.asset('assets/app/images/world/audio_start_ing_icon.png', width: 80.w)),
                  ),
                ),
                Positioned.fill(
                    top: 35.h,
                    child: Center(
                        child: Text(
                      '${((totalDuration / 1000).toStringAsFixed(0))}s',
                      style: TextStyle(color: Colors.white, fontSize: 13.sp, fontWeight: FontWeight.bold),
                    ))),
              ],
            ),
            Center(
                child: Text(
              controller!.playerState.isPlaying ? '播放中' : '点击播放',
              style: TextStyle(color: Colors.black, fontSize: 16.sp, fontWeight: FontWeight.bold),
            ))
          ],
        ));
  }
}
